/**
 * 
 */
package com.dp.util;

import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;

import com.dp.dao.TerminalDao;
import com.dp.pojo.TerminalPO;

/**
 * UA缓存
 * @author dingdaiyang
 * 
 */
@SuppressWarnings("unchecked")
public class UaCache {
	
	private static final Logger log = Logger.getLogger(UaCache.class);
//	private static UaCache uaCache;
	private TerminalDao terminalDao;
	// UA适配缓存  UA:适配终端数据
	private Map<String,TerminalPO> cache = new TreeMap<String,TerminalPO>();
	// 适配终端列表缓存
	private List<TerminalPO> list = new LinkedList<TerminalPO>(); 
	// 适配终端的ID缓存  适配终端的ID：适配终端数据 
	private Map<Long, TerminalPO> id_ter_map = new TreeMap<Long, TerminalPO>();
	
	private UaCache(TerminalDao terminalDao) {
		this.terminalDao = terminalDao;
		load();
	}
	
//	/**
//	 * 单例
//	 * @return
//	 */
//	public synchronized static UaCache getInstance() {
//		if (uaCache == null) {
//			uaCache = new UaCache();
//		}
//		return uaCache;
//	}

	public void reload() {
		cache.clear();
		load();
	}
	
	/**
	 * 加载缓存
	 */
	private synchronized void load() {
		
		List<TerminalPO> ter_list = null;
		TerminalPO ter = new TerminalPO();
		
		try {
			ter_list = terminalDao.getTerminalList();
			
			if(ter_list != null && ter_list.size() > 0){
				
				Map<String,TerminalPO> tmp = new TreeMap<String,TerminalPO>();
				Map<Long,TerminalPO> id_tmp = new TreeMap<Long,TerminalPO>();
				int ter_num = 0;
				list = ter_list; // 所有机型的缓存列表
				ter_num = ter_list.size();
				
				for (int i = 0; i < ter_num; i++) {  // 循环的机型
					// UA
					ter = (TerminalPO)getList(ter_list, i, ter);
					tmp.put(ter.getUser_agent(), ter);
					id_tmp.put(ter.getTerminal_id(), ter);
				}
				cache = tmp;// UA对应适配的缓存
				id_ter_map = id_tmp; //ID对应适配的缓存
			}
		} catch (SQLException e) {
			log.error("\t getTerminalList " + e);
		}
	}
	
	
	/**
	 * 优化
	 * @param list
	 * @param i
	 * @param sd
	 * @return
	 */
	private Object getList(List list, int i, Object sd){
		sd = list.get(i);
		return sd;
	}

	public Map<String, TerminalPO> getCache() {
		return cache;
	}

	public List<TerminalPO> getList() {
		return list;
	}
	
	public Map<Long, TerminalPO> getId_ter_map() {
		return id_ter_map;
	}
}